package top.zhangjianyong.tools.service.api.impl;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.zhangjianyong.tools.entity.guanjiangyuan.House;
import top.zhangjianyong.tools.entity.guanjiangyuan.People;
import top.zhangjianyong.tools.service.api.GuanjianyuanService;
import top.zhangjianyong.tools.service.mybatis.IHouseService;
import top.zhangjianyong.tools.service.mybatis.IPeopleService;
import top.zhangjianyong.tools.utils.ApiResponse;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ： zhangjianyong
 * @date ： 2023/7/5 12:32 PM
 */
@Service
public class GuanjianyuanServiceImpl implements GuanjianyuanService {

    @Autowired
    private IHouseService iHouseService;
    @Autowired
    private IPeopleService iPeopleService;

    @Override
    public ApiResponse searchHouse(String key) {
        List<House> list = iHouseService.searchHouse(key);
        return ApiResponse.success(list);
    }

    @Override
    public ApiResponse add(House house) {
        House house1 = iHouseService.qryByHouseNo(house.getHouseNo());
        if (house1 != null) return ApiResponse.fail("当前房号已存在,请不要重复添加！！！");
        iHouseService.save(house);
        return ApiResponse.success();
    }

    @Override
    public ApiResponse update(House house) {
        House house1 = iHouseService.getById(house.getId());
        if (house1 == null) return ApiResponse.fail("当前房间不存在，请检查！！！");
        iHouseService.updateById(house);
        return ApiResponse.success();
    }

    @Override
    public ApiResponse del(String id) {
        iHouseService.removeById(id);
        return ApiResponse.success();
    }

    @Override
    public ApiResponse peopleList(String houseNo) {
        List<People> list = iPeopleService.peopleList(houseNo);
        return ApiResponse.success(list);
    }

    @Override
    public ApiResponse peopleAdd(People people) {
        iPeopleService.save(people);
        return ApiResponse.success();
    }

    @Override
    public ApiResponse peopleUpdate(People people) {
        iPeopleService.updateById(people);
        return ApiResponse.success();
    }

    @Override
    public ApiResponse peopleDel(String id) {
        iPeopleService.removeById(id);
        return ApiResponse.success();
    }

    @Override
    public ApiResponse download(HttpServletResponse response) throws IOException {

        List<House> houses = iHouseService.list();
        List<People> people = iPeopleService.list();

        Map<Integer, List<House>> houseMap = groupHouse(houses);
        Map<String, List<People>> peopleMap = grouPeople(people);

        List<Integer> buildingNo = new ArrayList<>(houseMap.keySet());
        buildingNo.sort(Integer::compareTo);

        Workbook workbook = new HSSFWorkbook();

        for (Integer no : buildingNo) {
            List<House> list = houseMap.get(no);
            Sheet sheet = workbook.createSheet(no + "号楼");
            setHead(sheet);
            int row = 1;
            writeShell(sheet, list, peopleMap, row);
            for (int i = 0; i < 10; i++) {
                sheet.autoSizeColumn(i);
            }
        }

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("观江苑住户信息.xlsx", "UTF-8"));
        ServletOutputStream outputStream = response.getOutputStream();


        workbook.write(outputStream);
        workbook.close();

        return ApiResponse.success();
    }

    private void writeShell(Sheet sheet, List<House> list, Map<String, List<People>> peopleMap, int r) {
        for (House house : list) {
            List<People> orDefault = peopleMap.getOrDefault(house.getHouseNo(), null);
            if (null == orDefault) {
                Row row = sheet.createRow(r);
                Cell cell = row.createCell(0);
                cell.setCellValue(house.getHouseNo());

                cell = row.createCell(1);
                cell.setCellValue(house.getStatus());

                cell = row.createCell(2);
                cell.setCellValue(house.getStatus());

                cell = row.createCell(3);
                cell.setCellValue(house.getRegister());

                cell = row.createCell(4);
                cell.setCellValue("");

                cell = row.createCell(5);
                cell.setCellValue("");

                cell = row.createCell(6);
                cell.setCellValue("");

                cell = row.createCell(7);
                cell.setCellValue(house.getRemark());

                cell = row.createCell(8);
                cell.setCellValue("");

                cell = row.createCell(9);
                cell.setCellValue("");
                r++;
            } else {
                for (People people : orDefault) {
                    Row row = sheet.createRow(r);
                    Cell cell = row.createCell(0);
                    cell.setCellValue(house.getHouseNo());

                    cell = row.createCell(1);
                    cell.setCellValue(house.getStatus());

                    cell = row.createCell(2);
                    cell.setCellValue(house.getStatus());

                    cell = row.createCell(3);
                    cell.setCellValue(people.getName());

                    cell = row.createCell(4);
                    cell.setCellValue(people.getIdNo());

                    cell = row.createCell(5);
                    cell.setCellValue(people.getPhone());

                    cell = row.createCell(6);
                    cell.setCellValue(people.getHouseholdRegister());

                    cell = row.createCell(7);

                    cell.setCellValue((house.getRemark() + ";" + people.getRemark()).replace("null",""));

                    cell = row.createCell(8);
                    cell.setCellValue(people.getIsMaster());

                    cell = row.createCell(9);
                    cell.setCellValue(people.getIsLive());
                    r++;
                }
            }


        }
    }

    public void setHead(Sheet sheet) {
        Row row = sheet.createRow(0);

        Cell cell = row.createCell(0);
        cell.setCellValue("房号");

        cell = row.createCell(1);
        cell.setCellValue("房屋性质");

        cell = row.createCell(2);
        cell.setCellValue("房管通有无登记");

        cell = row.createCell(3);
        cell.setCellValue("姓名");

        cell = row.createCell(4);
        cell.setCellValue("身份证号码");

        cell = row.createCell(5);
        cell.setCellValue("手机号码");

        cell = row.createCell(6);
        cell.setCellValue("户籍");

        cell = row.createCell(7);
        cell.setCellValue("备注");

        cell = row.createCell(8);
        cell.setCellValue("是否户主");
        cell = row.createCell(9);
        cell.setCellValue("是否居住");
    }

    private Map<String, List<People>> grouPeople(List<People> people) {
        Map<String, List<People>> map = new HashMap<>();
        for (People p : people) {
            String houseNo = p.getHouseNo();
            List<People> list = map.getOrDefault(houseNo, new ArrayList<>());
            list.add(p);
            map.put(houseNo, list);
        }

        return map;
    }

    public void sort(List<House> list) {
        //排序
        list.sort(((o1, o2) -> {
            String houseNo1 = o1.getHouseNo();
            String houseNo2 = o2.getHouseNo();
            String[] split1 = houseNo1.split("-");
            String[] split2 = houseNo2.split("-");
            int length = split1.length;
            if (split2.length > split1.length) {
                length = split2.length;
            }
            for (int i = 0; i < length; i++) {
                int v1 = 0, v2 = 0;
                if (split1.length > i) {
                    v1 = Integer.valueOf(split1[i]);
                }
                if (split2.length > i) {
                    v2 = Integer.valueOf(split2[i]);
                }
                if (v1 == v2) continue;
                return v2 - v1;
            }
            return 0;
        }));
    }

    public Map<Integer, List<House>> groupHouse(List<House> list) {
        //排序
        sort(list);

        Map<Integer, List<House>> map = new HashMap<>();
        for (House house : list) {
            Integer buildingNo = house.getBuildingNo();
            List<House> li = map.getOrDefault(buildingNo, new ArrayList<>());
            li.add(house);
            map.put(buildingNo, li);
        }
        return map;
    }

}
